%function london_blink_remover_april2004
% this file removes blinks from london eye data and combines matlab timeing
% data with the eye tracker data in to one file (*B.mat)


clear;
clc;
close all;
column=12;
scnsize = get(0,'ScreenSize');

% c=define_colors(1);
% c.BACKGROUND=c.BLACK;
% c.PRO=c.RED;
% c.ANTI=c.GREEN;

redraw=1;
%%% Reading ascii format data
%cd C:\_bcoe\london_eyedata;
%cd D:\london_eyedata;
%cd 'C:\_bcoe\London_Eye_Data\2004-01-06'
eye_files = dir('*.eye'); % find all eye files

    


%fp_num=2;
for fp_num=1:length(eye_files)
eye_name=eye_files(fp_num).name;
mat_name=[eye_name(1:length(eye_name)-3) 'mat'];
load(mat_name);
fp = fopen(eye_name);
if fp==-1
    disp(['can not open file: ' eye_files]);
    return
end

    
%     set trial states and their relative timing in secs
%     S_ITI=1;     dur_iti=2;  t_state(S_ITI    ,:)=' ITI    ';
%     S_FIX=2;     dur_fix=3;  t_state(S_FIX    ,:)=' FIX    ';
%     S_GAP=3;                 t_state(S_GAP    ,:)=' GAP    ';% random duration
%     S_CUE_TGT=4; dur_c_t=.1; t_state(S_CUE_TGT,:)=' CUE_TGT'; 
%     S_BLACK=5;   dur_blk=3;  t_state(S_BLACK  ,:)=' BLACK  '; 
%     A.name=mat_name
    
    %%% Read Header Information from file [rows, white_spaces]
    h_version  =fgets(fp); version  =h_version(find(h_version==':')+1:end);
    h_format   =fgets(fp); format   =h_format (find(h_format ==':')+1:end);
    h_subject  =fgets(fp); subject  =h_subject(find(h_subject==':')+1:end);  
    h_date     =fgets(fp); date     =h_date(find(h_date==':')+1:end);  
    h_disc     =fgets(fp); disc     =h_disc(find(h_disc==':')+1:end);
    h_pts_rec  =fgets(fp); pts_rec  =h_pts_rec(find(h_pts_rec==':')+1:end);
    h_cali_off =fgets(fp); cali_off =h_cali_off(find(h_cali_off==':')+1:end);
    h_cali_area=fgets(fp); cali_area=h_cali_area(find(h_cali_area==':')+1:end);
    h_rate     =fgets(fp); rate     =h_rate(find(h_rate==':')+1:end);
    h_space    =fgets(fp); space    =h_space(find(h_space==':')+1:end);
    h_headers  =fgets(fp); headers  =h_headers(find(h_headers==':')+1:end);
    
    %%% data read
    rdata=fscanf(fp,'%d',[1,inf]);
    fclose(fp);
    data=reshape(rdata,column,length(rdata)/column)';
    clear rdata
	
    d_COUNTER=1;
    d_TIME=2;
    d_SET=3;
    d_Pupil_H=4;
    d_Pupil_V=5;
    d_CR_H=6;
    d_CR_V=7;
    d_SCREEN_H=8;
    d_SCREEN_V=9;
    d_DIAM_H=10;
    d_DIAM_V=11;
    d_OBJECTS=12;
    
    datac=data(data(:,d_SET)>0,:);
    
    counter =datac(:,d_COUNTER );
    eye_time=datac(:,d_TIME    );
	data_set=datac(:,d_SET     );
    pup_x   =datac(:,d_Pupil_H );
    pup_y   =datac(:,d_Pupil_V );
    cr_x    =datac(:,d_CR_H    );
    cr_y    =datac(:,d_CR_V    );
    eye_x   =datac(:,d_SCREEN_H);
    eye_y   =-datac(:,d_SCREEN_V); % reversed for london's eye tracker
    diam_x  =datac(:,d_DIAM_H  );
    diam_y  =datac(:,d_DIAM_V  );
    eye_type=datac(:,d_OBJECTS );
    clear  data
    
	eye_time1=eye_time;
	[cnt val]=hist(data_set,min(data_set):max(data_set));[cnt' val'];
% 	fig(1);clf;hold on
% 	plot(eye_time)
% 	h=plot(eye_time1,'r')
	for i=1:length(val)
		first=min(find(diff(data_set)==1))+1;
% 		vline(first)
		eye_time1(first:end)=eye_time1(first:end)+eye_time(first-1)+16.666666667;
		data_set(first:end)=data_set(first:end)-1;
% 		delete(h)
% 		h=plot(eye_time1,'r')
% 		drawnow
    end
    eye_time=eye_time1;
    
    if ~isfield(A,'pixperdeg')
        pixperdeg=25.2857;% just for andrews old data
    else
        pixperdeg=A.pixperdeg;
    end
    
    if redraw
        fig(50);
        set(50,'Position',[5 (scnsize(4)*.6)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_name,'NumberTitle','off');
        clf;cla;hold on;tickout
        set(gca,'Position',[ .05 .11 .9 .81]);
        
%          plot(eye_time(eye_type>0),eye_x(eye_type>0),'.-');
%         plot(eye_time(eye_type>0),eye_y(eye_type>0),'.-r');
    end
    eye_x1=(eye_x-mean(eye_x(eye_type>0)))/pixperdeg;
    eye_y1=(eye_y-mean(eye_y(eye_type>0)))/pixperdeg;
    vel_x=[0;diff(eye_x1)./diff(eye_time/1000)];
    vel_y=[0;diff(eye_y1)./diff(eye_time/1000)];
    speed=sqrt(vel_x.^2+vel_y.^2);
    %%%% find blinks
    blink=(eye_type<1)*1;
    if redraw
        %%%%%%plot(eye_time,vel_x,'g');
        %%%%%%plot(eye_time,vel_y,'y');
        h_speed=plot(eye_time,speed,'.-g');
        axis tight;ylim([-50 400])
        plot(eye_time,eye_x1,'.-b');
        plot(eye_time,eye_y1,'.-r');
        plot(eye_time(eye_type<1),eye_x1(eye_type<1),'.c');
        plot(eye_time(eye_type<1),eye_y1(eye_type<1),'.m');
        hline(50);
        h_blink=hplot(eye_time,blink*50);
    end
    
    speed2=speed;
    speed2(find((abs(eye_x1)>40|abs(eye_y1)>40)&speed<50))=100;
    speed2(1)=1;% these are set to prevent searches for fixation prior to recording
    speed2(end)=1;% these are set to prevent searches for fixation after recording
    x1=eye_x1;
    y1=eye_y1;
    s_x1=x1;
    s_y1=y1;
    i=1;
    end_eye=[];
    start_eye=[];
    s_start_eye=[];
    start_blink=[];
    end_blink=[];
    while sum(diff(blink)==1)>0
        start_blink(i)=min(find(diff([0;blink])== 1));
        end_blink(i)  =min(find(diff([blink;0])==-1));
        if redraw
            xlim([eye_time(max([1 start_blink(i)-50])) eye_time(min([length(eye_time) end_blink(i)+50]))])
            a=vline(eye_time([start_blink(i) end_blink(i)]),'m');
            pause(.2);
        end
        if max(speed(start_blink(i): end_blink(i)))>750		
            [val loc]=max(speed(start_blink(i):end_blink(i)));
            find_max=start_blink(i)+loc-1;		
            speed2(find(speed(start_blink(i):end_blink(i))==0)+(start_blink(i)-1))=val;
            speed2(1)=1;% these are set to prevent searches for fixation prior to recording
            speed2(end)=1;% these are set to prevent searches for fixation after recording

            if redraw
                delete(h_speed);
                h_speed=plot(eye_time,speed2/10,'.-g');
            end
            %%%%%%%%%%%%%%min speed limit is set to 15
            
            min_speed=15;
            p=100;
            min_range=max([1;find_max-p]);
            while all(speed2(min_range:find_max)>min_speed | speed2(min_range:find_max)==0) & min_range>1
                p=p+100;
                min_range=max([1;find_max-p]);
            end
            start_blink2(i)=(max(find(speed2(min_range:find_max)<min_speed & speed2(min_range:find_max)>0))+min_range-1);
            
            p=100;
            max_range=min([end_blink(i)+p length(speed2)]);
            while all(speed2(find_max:max_range)>min_speed | speed2(find_max:max_range)==0) & max_range<length(speed2)
                p=p+100;
                max_range=min([find_max+p length(speed2)]);
            end
            clear p;
            end_blink2(i)=(min(find(speed2(find_max:max_range)<min_speed & speed2(find_max:max_range)>0))+find_max-1);
            
            if redraw
                b=vline(eye_time([start_blink2(i) end_blink2(i)]),'k');
                plot(eye_time(start_blink2(i)),x1(start_blink2(i)),'ob')
                plot(eye_time(start_blink2(i)),y1(start_blink2(i)),'or')
                plot(eye_time(end_blink2(i)),x1(end_blink2(i)),'ob')
                plot(eye_time(end_blink2(i)),y1(end_blink2(i)),'or')
            end
            range=(start_blink2(i):end_blink2(i));
            inc_x=diff(x1([range(1) range(end)]))/(length(range)-.999);
            inc_y=diff(y1([range(1) range(end)]))/(length(range)-.999);
                %stupid thing... but only for one blink, in one file, in all of my data
                %does the above algorithm not work. so i made it .999
                %instead of 1                
            if inc_x
                x1(range)=(x1(range(1)):inc_x:x1(range(end)))';
            else
                x1(range)=x1(range(1));
            end
            if inc_y
                y1(range)=(y1(range(1)):inc_y:y1(range(end)))';
            else
                y1(range)=y1(range(1));
            end
            if redraw
                plot(eye_time(range),x1(range),'ob');
                plot(eye_time(range),y1(range),'or');
            end            
            % check to make sure that there are not two blinks in a row check            
            if blink(min(range(range>4))-3)==6 %| blink(min(range(range>4))-3)==4 %check 3 points back
                blink(max(find(diff(blink(1:min(range)))==6))+1:max(range)-1)=1;
                speed2(max(3,min(range)-2):min(range))=100;
            else
                blink(range)=6;
                blink([min(range(range>1))-1 max(range)])=0;
            end
        else
            b=vline(0);
            start_blink2(i)=start_blink(i);
            end_blink2(i)=end_blink(i);
            
            blink(start_blink(i)+1:end_blink(i))=4;
            blink([start_blink(i) end_blink(i)])=0;
        end
        
        if redraw
            delete(h_blink)
            h_blink=hplot(eye_time,blink*50);     
            fig(51);
            set(51,'Position',[5 (scnsize(4)*.25)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_name,'NumberTitle','off');
            clf;cla;hold on;tickout
            subplot('Position',[0.690141 0.0857143 0.299296 0.814286]);hold on;axis square; axis([-30 30 -30 30])
            temp_range=([(max([1 start_blink2(i)-25])):(min([length(eye_time) end_blink2(i)+25]))]);
            plot(eye_x1(temp_range),eye_y1(temp_range),'.-r');
            plot(x1(min(temp_range):end_blink2(i)),y1(min(temp_range):end_blink2(i)),'o-');
            subplot('Position',[0.0334507 0.0761905 0.608275 0.814286]);hold on;
            plot(eye_time(temp_range),eye_x1(temp_range),'.-c')
            plot(eye_time(temp_range),eye_y1(temp_range),'.-m');
            plot(eye_time(min(temp_range):end_blink2(i)),x1(min(temp_range):end_blink2(i)),'.-b')
            plot(eye_time(min(temp_range):end_blink2(i)),y1(min(temp_range):end_blink2(i)),'.-r');
            axis tight; ylim([-30 30])
            fig(50);
            pause(1)
            fig(50); % again in case the user plays with the figs            
            delete(a)
            delete(b)
        end % redraw
        i=i+1;
    end
    if redraw       
        axis auto
        ylim([-5 5])
    end % redraw

    fig(fp_num);
    set(fp_num,'Position',[5 (scnsize(4)*.6)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_name,'NumberTitle','off');
    clf;cla;hold on;tickout
    set(gca,'Position',[ .05 .11 .9 .81]);

    vel_x1=[0;diff(x1)./diff(eye_time/1000)];
    vel_y1=[0;diff(y1)./diff(eye_time/1000)];
    speed1=sqrt(vel_x1.^2+vel_y1.^2);
    %plot(eye_time,vel_x,'g');
    %plot(eye_time,vel_y,'y');
    plot(eye_time,speed1,'.-g');
    plot(eye_time(blink>4),speed1(blink>4),'.y');
    plot(eye_time,x1,'.-b');
    plot(eye_time,y1,'.-r');
    plot(eye_time(blink>4),x1(blink>4),'.c');
    plot(eye_time(blink>4),y1(blink>4),'.m');
    plot(eye_time,blink*10,'k')
    axis tight;ylim([-100 500])
    hline(50);
    
    if ~isfield(A,'colors')% just for andrews old data
        A.colors=define_colors;
        A.colors.PRO=A.colors.GREEN;
        A.colors.ANTI=A.colors.RED;
        A.colors.BACKGROUND=A.colors.D_GREY        
    end
	% change the 32 based psychophysics toolbox colors into
	% the 0-1 based stuff for matlab 
    names = fieldnames(A.colors);
	for i=1:length(names)
		colors.(names{i})=A.colors.(names{i})/31;
	end
	
	B=A;
    B.colors=colors;
    B.eye_x=x1;
    B.eye_x_raw=eye_x1;
    B.eye_y=y1;
    B.eye_y_raw=eye_y1;
    B.vel_x=vel_x1;
    B.vel_y=vel_y1;
    B.speed=speed1;
    B.time=eye_time;
    B.blink=blink;
    
    
    
    a_name=mat_name(1:length(mat_name)-4)
%     day=num2str(A.clock(3));
%     month=num2str(A.clock(2));
% 	if length(day)==1;
% 		day=['0' day];
% 	end
% 	if length(month)==1;
% 		month=['0' month];
% 	end
% 	B.name=[num2str(A.clock(1)) '_' month '_' day  '_'  a_name];
	B.name=a_name;

    save([B.name 'B.mat'],'B')
end %for fp_num

   
   
   